<style></style>
<template>
  <!-- 头部搜索 -->
  <div style="margin-bottom: 10px;">
    <span style="margin-right: 10px;">投诉内容:</span>
    <el-input v-model="searchText" style="width: 240px;margin-right: 10px;" placeholder="请输入投诉内容" />
    <el-button :icon="Search" type="primary" @click="btnSearch()" plain>搜索</el-button>
    <!-- 打开添加弹窗 -->
    <el-button type="success" @click="Add()" plain>
      <el-icon>
        <Plus />
      </el-icon>添加
    </el-button>
  </div>

  <!-- 表格 -->
  <!-- 设置表格中的语言配置为中文 -->
  <el-config-provider :locale="zhCn">
    <el-table :data="tableData" row-key="Chargesid" style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column label="项目编号" prop="Chargesid" width="200" align="center" />
      <el-table-column label="收费名称" prop="ChargesName" width="300" align="center" />
      <el-table-column label="创建时间" prop="Createtime" align="center">
          <template #default="scope">
                      <span>{{ convertDateTime(scope.row.Createtime) }}</span>
                    </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="warning" :icon="Edit" size="small" @click="handleEdit(scope.$index, scope.row)"
            plain>编辑</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(scope.$index, scope.row)"
            plain>删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <!-- 分页 -->
    <div class="demo-pagination-block" style="margin-top: 10px;">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50, 100]"
        :small="small" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </el-config-provider>

  <!-- 添加/编辑Form -->
  <el-config-provider :locale="zhCn">
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500" :destroy-on-close="true"
      :before-close="clearForm">
      <el-form :model="form" :rules="rules" ref="ruleFormRef" status-icon :label-position="labelPosition"
        class="demo-form-inline">

        <!-- 项目名称 -->
        <el-form-item label="项目名称" :label-width="formLabelWidth" prop="ChargesName">
          <el-input v-model="form.ChargesName" placeholder="请输入项目名称" autocomplete="off" />
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clearForm">取消</el-button>
          <el-button type="primary" @click="btnSave(ruleFormRef)">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-config-provider>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import axios from 'axios'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { ElMessage, ElMessageBox, FormRules, FormInstance } from 'element-plus'
import { ElTable } from 'element-plus'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'

//存储表格数据信息
let tableData = ref([]);

//搜索信息
var searchText = ref("");

//控制打开/关闭模态框
const dialogFormVisible = ref(false)
//表单输入框前标题宽度
const formLabelWidth = '100px'
//弹出层标题
var dialogTitle = ref("")

//页面加载方法
onMounted(() => {
  bindData(currentPage.value, pageSize.value, searchText.value);
})

//存储表单数据
var form = ref({
  Chargesid: 0,
  ChargesName: ''
})

function Add() {
  dialogTitle.value = "添加收费项目";
  dialogFormVisible.value = true;
}

const handleEdit = (index, row) => {
  dialogTitle.value = "修改收费项目";
  dialogFormVisible.value = true;
  form.value = row;
}

function btnSave(formEl) {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      axios({
        method: form.value.Chargesid > 0 ? 'put' : 'post',
        data: form.value,
        url: 'https://localhost:7090/api/ChargesInfo',
        headers: { 'Content-Type': 'application/json' }
      }).then((res) => {
        if (res) {
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          clearForm()
          bindData(currentPage.value, pageSize.value, searchText.value);
        } else {
          ElMessage({
            message: '保存失败',
            type: 'error',
          })
        }
      }).catch((err) => {
        ElMessage({
          message: err,//"网络异常，请联系管理员!!!"
          type: 'error',
        })
      })
    } else {
      return false
    }
  })
}

//验证
const ruleFormRef = ref();
//添加表单校验
const rules = reactive({
  ChargesName: [{
    required: true,//必填
    message: '请输入项目名称',
    trigger: 'change'
  }]
})

//删除
var handleDelete = (index, row) => {
  var chargesid;
  ElMessageBox.confirm(
    '确定要删除吗?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    chargesid = row.Chargesid;
    axios.delete(`https://localhost:7090/api/ChargesInfo/?chargesid=${chargesid}`)
      .then(function (res) {
        if (res.data == true) {
          ElMessage({
            type: 'success',
            message: "删除成功"
          })
          clearForm()
          bindData(currentPage.value, pageSize.value, searchText.value);
        } else {
          ElMessage({
            type: 'warning',
            message: "删除失败" + res.data.msg
          })
        }
      }).catch(() => {
        ElMessage({
          type: 'warning',
          message: "删除失败!"
        })
      })

  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '用户取消操作',
    })
  })
}


//绑定数据表格
function bindData(page, limit, chargesName) {
  axios.get(`https://localhost:7090/api/ChargesInfo?page=${page}&limit=${limit}&chargesName=${chargesName}`)
    .then(function (response) {
      tableData.value = response.data.data;
      total.value = response.data.total;
    })
}


//模糊查询
function btnSearch() {
  bindData(currentPage.value, pageSize.value, searchText.value);
}

//清除表单
function clearForm() {
  dialogFormVisible.value = false;
  form.value = {
    Chargesid: 0,
    ChargesName: ''
  };
}

//分页
const currentPage = ref(1)//当前页数
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
const pageSize = ref(5)//每页条数
const total = ref(0)//总数据量

//切换每页条数
const handleSizeChange = (val) => {
  bindData(currentPage.value, pageSize.value, searchText.value);
}

//切换页数
const handleCurrentChange = (val) => {
  bindData(currentPage.value, pageSize.value, searchText.value);
}

//转换日期时间
function convertDateTime(dateStr) {
  var datetimeObj = new Date(dateStr);
  var year = datetimeObj.getFullYear();
  var month = ("0" + (datetimeObj.getMonth() + 1)).slice(-2);
  var day = ("0" + datetimeObj.getDate()).slice(-2);
  var hours = ("0" + datetimeObj.getHours()).slice(-2);
  var minutes = ("0" + datetimeObj.getMinutes()).slice(-2);
  var seconds = ("0" + datetimeObj.getSeconds()).slice(-2);
  var formattedDate = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  return formattedDate;
}

</script>